package com.hotel.user.controller;

import com.hotel.common.entity.Role;
import com.hotel.common.utils.Result;
import com.hotel.user.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/roles")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/{id}")
    public Result<Role> getRoleById(@PathVariable("id") Long id) {
        return roleService.getRoleById(id);
    }

    @GetMapping("/user/{userId}")
    public Result<List<Role>> getRolesByUserId(@PathVariable("userId") Long userId) {
        return roleService.getRolesByUserId(userId);
    }

    @GetMapping("/code/{roleCode}")
    public Result<Role> getRoleByCode(@PathVariable("roleCode") String roleCode) {
        return roleService.getRoleByCode(roleCode);
    }

    @GetMapping
    public Result<List<Role>> getAllRoles() {
        return roleService.getAllRoles();
    }

    @PostMapping
    public Result<Long> createRole(@RequestBody Role role) {
        return roleService.createRole(role);
    }

    @PutMapping
    public Result<Void> updateRole(@RequestBody Role role) {
        return roleService.updateRole(role);
    }

    @DeleteMapping("/{id}")
    public Result<Void> deleteRole(@PathVariable("id") Long id) {
        return roleService.deleteRole(id);
    }

    @PostMapping("/{roleId}/permissions/{permissionId}")
    public Result<Void> assignPermission(@PathVariable("roleId") Long roleId, @PathVariable("permissionId") Long permissionId) {
        return roleService.assignPermission(roleId, permissionId);
    }

    @DeleteMapping("/{roleId}/permissions/{permissionId}")
    public Result<Void> removePermission(@PathVariable("roleId") Long roleId, @PathVariable("permissionId") Long permissionId) {
        return roleService.removePermission(roleId, permissionId);
    }

    @GetMapping("/permissions")
    public Result<List<Role>> getRolesWithPermissions() {
        return roleService.getRolesWithPermissions();
    }

    @PostMapping("/permissions")
    public Result<Void> assignPermissionsToRole(@RequestBody Map<String, Object> request) {
        Long roleId = Long.valueOf(request.get("roleId").toString());
        List<Long> permissionIds = (List<Long>) request.get("permissionIds");
        return roleService.assignPermissionsToRole(roleId, permissionIds);
    }

    @DeleteMapping("/{roleId}/permissions")
    public Result<Void> removeAllPermissionsFromRole(@PathVariable Long roleId) {
        return roleService.removeAllPermissionsFromRole(roleId);
    }
}